package com.rrd.dw.mr.gzip.kafka;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.ucredit.babel.common.model.BaseModel;
import com.ucredit.babel.common.model.RecordType;
import com.ucredit.babel.common.model.tongdun.TongdunRiskDetail;
import com.ucredit.babel.common.model.tongdun.TongdunRiskReport;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper.Context;

import java.io.IOException;

/**
 * 同盾风险报告-贷前审核借款事件详情
 *
 * @author xj
 */

public class TongdunRiskDetailConditionsInfoParse extends ParseBase {
    private Text val = new Text();
    private Text key = new Text();
    private StringBuilder sb;
    private StringBuilder ruleSb = new StringBuilder(500);
    private StringBuilder conditionSb = new StringBuilder(500);
    private StringBuilder detailSb = new StringBuilder(500);

    /**
     * 同盾风险报告-贷前审核借款事件详情
     *
     * @param model
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public boolean parseJob(Context context, BaseModel<?> model, String successful) throws IOException, InterruptedException {
        TongdunRiskReport obj = (TongdunRiskReport) model;
        TongdunRiskDetail data = obj.getTongdunRiskDetail();
        JSONObject detail = data.getDetail() == null ? new JSONObject() : JSON.parseObject(data.getDetail());
        JSONArray rules = detail.getJSONArray("rules") == null ? new JSONArray() : detail.getJSONArray("rules");
        sb = getBaseInfo(obj, successful);
        //是否成功
        sb.append(detail.getString("success") == null ? "" : detail.getString("success")).append(CRT001);
        //若success为false，此处显示错误码
        sb.append(detail.getString("reasonCode") == null ? "" : detail.getString("reasonCode")).append(CRT001);
        //错误提示信息
        sb.append(detail.getString("reasonDesc") == null ? "" : detail.getString("reasonDesc")).append(CRT001);
        setFileNum(20);
        for (Object rule : rules) {
            JSONObject r = (JSONObject) rule;
            JSONArray conditions = r.getJSONArray("conditions") == null ? new JSONArray() : r.getJSONArray("conditions");
            ruleSb.delete(0, ruleSb.length());
            //命中规则
            ruleSb.append(r.getString("ruleId") == null ? "" : r.getString("ruleId")).append(CRT001);
            //决策结果
            ruleSb.append(r.getString("decision") == null ? "" : r.getString("decision")).append(CRT001);
            //权重分数
            ruleSb.append(r.getString("score") == null ? "" : r.getString("score")).append(CRT001);

            for (Object condition : conditions) {
                JSONObject c = (JSONObject) condition;
                conditionSb.delete(0, conditionSb.length());
                //规则的类型
                conditionSb.append(c.getString("type") == null ? "" : c.getString("type")).append(CRT001);
                //计算结果
                conditionSb.append(c.getString("result") == null ? "" : c.getString("result")).append(CRT001);
                //hits JSON字符换
                boolean haveHits = write(context, c, "hits");
                //resultsForDim JSON字符换
                boolean haveResultsForDim = write(context, c, "resultsForDim");
                //hitsForDim JSON字符换
                boolean haveHitsForDim = write(context, c, "hitsForDim");
                if (!haveHits && !haveResultsForDim && !haveHitsForDim) {
                    key.set(getKey());
                    val.set((sb.toString() + ruleSb.toString() + conditionSb.toString()).replace("\n", " ").replace("\r", " "));
                    context.write(key, val);
                }
            }
            if(conditions.size() <= 0) {
                key.set(getKey());
                val.set((sb.toString() + ruleSb.toString()).replace("\n", " ").replace("\r", " "));
                context.write(key, val);
            }
        }
        return true;
    }

    private boolean write(Context context, JSONObject condition, String field) throws IOException, InterruptedException {
        JSONArray hits = condition.getJSONArray(field) == null ? new JSONArray() : condition.getJSONArray(field);
        if(hits.size() <= 0) {
            return false;
        }
        for (Object hit : hits) {
            JSONObject h = (JSONObject) hit;
            detailSb.delete(0, detailSb.length());
            detailSb.append(field).append(CRT001);
            detailSb.append(h.getString("industryDisplayName") == null ? "" : h.getString("industryDisplayName")).append(CRT001);
            detailSb.append(h.getString("count") == null ? "" : h.getString("count")).append(CRT001);
            detailSb.append(h.getString("overdueAmount") == null ? "" : h.getString("overdueAmount")).append(CRT001);
            detailSb.append(h.getString("overdueCount") == null ? "" : h.getString("overdueCount")).append(CRT001);
            detailSb.append(h.getString("overdueDay") == null ? "" : h.getString("overdueDay")).append(CRT001);
            detailSb.append(h.getString("overdueTime") == null ? "" : h.getString("overdueTime")).append(CRT001);
            detailSb.append(h.getString("dimType") == null ? "" : h.getString("dimType")).append(CRT001);
            detailSb.append(h.getString("originalDimType") == null ? "" : h.getString("originalDimType")).append(CRT001);
            detailSb.append(h.getString("matchDimType") == null ? "" : h.getString("matchDimType")).append(CRT001);
            key.set(getKey());
            val.set((sb.toString() + ruleSb.toString() + conditionSb.toString() + detailSb.toString()).replace("\n", " ").replace("\r", " "));
            context.write(key, val);
        }
        return true;
    }

    @Override
    public String getSubType() {
        return ".detail_conditions";
    }

    @Override
    public String getTableName() {
        return "kafka_babel_tongdun_risklend_detail_conditions_info_ana_inc";
    }

    @Override
    public String getType() {
        return RecordType.TONGDUN_RISK_REPORT.toString();
    }

    @Override
    public String getComment() {
        return "同盾风险报告-贷前审核借款事件详情";
    }
}
